#include "func_iic_master.h"
#include "string.h"
#include "usb_com.h"
#include "iicMaster.h"
#include "mem_malloc.h"

static unsigned char *readData;
static unsigned char *sendData;
static unsigned char readOk;
static unsigned char addr;
static unsigned char readLen;



/// @brief usb设定参数
/// @param cmd
/// @param subCmd
/// @param data
void iic_master_set_param(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_SET_PARAM, (void *)COM_OK);
}

/// @brief usb接收到需要发送的数据
/// @param cmd
/// @param subCmd
/// @param data
void iic_master_write_data(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    m_malloc(sendData, data[2] - 9);
    if (sendData == 0)
    {
        usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_WRITE, (void *)COM_MEM);
    }
    else
    {
        memcpy(sendData, &data[8], data[2] - 9);
        iic_write_bytes(data[7], sendData, data[2] - 9, (data[5] << 8) + data[6]);
    }

}

/// @brief usb上传接收到的数据
/// @param cmd
/// @param subCmd
/// @param param
void iic_master_read_update(unsigned char cmd, unsigned char subCmd, void *param)
{
    unsigned char sendData[USB_PORT_SIZE] = {0};
    sendData[0] = 0xaa;
    sendData[1] = 0x55;
    sendData[2] = readLen + 8;
    sendData[3] = COMM_IIC_MASTER;
    sendData[4] = COMM_SUB_IIC_MASTER_READ;
    sendData[5] = readOk;
    sendData[6] = addr;
    if (readData)
    {
        memcpy(&sendData[7], readData, readLen);
        m_free(readData);
    }

    sendData[readLen + 7] = chksum(sendData, readLen + 7);
    usb_send(sendData, readLen + 8);
}

/// @brief 硬件IIC读取数据
/// @param cmd
/// @param subCmd
/// @param data
void iic_master_read_data(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    addr = data[5] + 1;
    readLen = data[8];
    m_malloc(readData, BUFF_SIZE);
    if (readData == 0)
    {
        readOk = COM_MEM;
        usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_READ, (void *)0);
    }
    else
    {
        iic_read_bytes(addr, readData, data[8], (data[6] << 8) + data[7]);
    }

}

/// @brief iic 回调
/// @param state
void iic_callback(unsigned char state)
{
    switch (state)
    {
        case IIC_READ_OK:
            readOk = COM_OK;
            usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_READ, (void *)0);
            break;
        case IIC_READ_FAIL:
            readOk = COM_TIMEOUT;
            usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_READ, (void *)0);
            break;
        case IIC_WRITE_OK:
            m_free(sendData);
            usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_WRITE, (void *)COM_OK);
            break;
        case IIC_WRITE_FAIL:
            m_free(sendData);
            usb_cmd(COMM_IIC_MASTER, COMM_SUB_IIC_MASTER_WRITE, (void *)COM_TIMEOUT);
            break;
        default:
            break;
    }
}

